<template>
    <div class="app-container">
      <div class="filter-container" style="display: flex; justify-content: space-between; margin-bottom: 20px;">
        <div class="filter-left">
          <el-form :inline="true" :model="listQuery" class="demo-form-inline">
            <el-form-item label="任务名称">
              <el-input
                v-model="listQuery.name"
                placeholder="请输入任务名称"
                style="width: 200px;"
                size="mini"
                clearable
                @keyup.enter.native="handleFilter"
                @clear="handleFilter"
              />
            </el-form-item>
            <el-form-item label="全宗号">
              <el-input
                v-model="listQuery.qzh"
                placeholder="请输入全宗号"
                style="width: 150px;"
                size="mini"
                clearable
                @keyup.enter.native="handleFilter"
                @clear="handleFilter"
              />
            </el-form-item>
            <el-form-item label="状态">
              <el-select
                v-model="listQuery.status"
                placeholder="请选择状态"
                clearable
                size="mini"
                style="width: 120px"
                @change="handleFilter"
              >
                <el-option label="未启动" :value="0" />
                <el-option label="已启动" :value="1" />
                <el-option label="运行中" :value="2" />
                <el-option label="已暂停" :value="3" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-search"
                @click="handleFilter"
              >
                搜索
              </el-button>
              <el-button
                size="mini"
                icon="el-icon-refresh"
                @click="handleReset"
              >
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="filter-right">
          <el-button size="mini" type="primary" @click="handleAdd">
            添加任务
          </el-button>
          <el-button size="mini" type="info" @click="viewAllQueue" style="margin-left: 10px;">
            查看全部队列
          </el-button>
        </div>
      </div>
  
      <div class="myTable" style="min-height: 600px;">
        <el-table 
          :key="tableKey" 
          :data="list" 
          fit 
          size="mini" 
          highlight-current-row 
          style="width: 100%;"
        >
          <el-table-column label="ID" prop="id" align="center" min-width="50" />
          <el-table-column label="任务名称" prop="name" align="center" min-width="150" />
          <el-table-column label="全宗号" prop="qzh" align="center" min-width="100" />
          <el-table-column label="Ollama地址" prop="ollama_url" align="center" min-width="200" show-overflow-tooltip />
          <el-table-column label="创建时间" prop="create_time" align="center" min-width="150" />
          <el-table-column label="更新时间" prop="update_time" align="center" min-width="150" />
          <el-table-column label="数据限制" prop="limit" align="center" min-width="100">
            <template slot-scope="{row}">
              {{ row.limit || '无限制' }}
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="status" align="center" min-width="100">
            <template slot-scope="{row}">
              <div v-if="row.status === 1">
                <span class="statusPie success" />
                <span class="text">已启动</span>
              </div>
              <div v-else-if="row.status === 2">
                <span class="statusPie warning" />
                <span class="text">运行中</span>
              </div>
              <div v-else-if="row.status === 3">
                <span class="statusPie info" />
                <span class="text">已暂停</span>
              </div>
              <div v-else>
                <span class="statusPie danger" />
                <span class="text">未启动</span>
              </div>
            </template>
          </el-table-column>
  
          <el-table-column label="操作" align="center" min-width="280" class-name="small-padding fixed-width">
            <template slot-scope="{row,$index}">
              <el-button 
                v-if="row.status === 0"
                type="success" 
                size="mini" 
                @click="handleStart(row)"
              >
                启动
              </el-button>
              <el-button 
                v-else
                type="info" 
                size="mini" 
                @click="handleStop(row)"
              >
                停止
              </el-button>
              <el-button 
                type="primary" 
                size="mini" 
                @click="handleEdit(row)"
              >
                编辑
              </el-button>
              <el-button 
                size="mini" 
                type="danger" 
                @click="handleDelete(row,$index)"
              >
                删除
              </el-button>
              <el-button 
                size="mini" 
                type="warning" 
                @click="viewQueue(row)"
              >
                查看队列
              </el-button>
            </template>
          </el-table-column>
        </el-table>
  
        <pagination 
          v-show="total>0"
          size="mini"
          :total="total"
          :page.sync="listQuery.page"
          :limit.sync="listQuery.limit"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @pagination="getList" 
        />
      </div>
  
      <!-- 添加/编辑对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
        <el-form 
          ref="dataForm" 
          :rules="rules" 
          :model="temp" 
          label-position="right" 
          label-width="100px"
        >
          <el-form-item label="任务名称" prop="name">
            <el-input v-model="temp.name" placeholder="请输入任务名称" />
          </el-form-item>
          <el-form-item label="全宗号" prop="qzh">
            <el-input v-model="temp.qzh" placeholder="请输入全宗号" />
          </el-form-item>
          <el-form-item label="lbh" prop="lbh">
            <el-input v-model="temp.lbh" placeholder="请输入类别号" />
          </el-form-item>
          <el-form-item label="Ollama地址" prop="ollama_url">
            <el-select v-model="temp.ollama_url" placeholder="请选择Ollama服务地址" filterable clearable style="width: 100%"><el-option v-for="item in ollamaOptions" :key="item.value" :label="item.label" :value="item.value" /></el-select>
          </el-form-item>
          <el-form-item label="数据限制" prop="limit" style="width: 100%;">
            <el-input-number  style="width: 100%;"
              v-model="temp.limit" 
              :min="0" 
              controls-position="right"
              placeholder="请输入数据限制，0表示无限制" 
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveData">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { api } from '@/api/template'
  import Pagination from '@/components/Pagination'
  
  export default {
    name: 'ExtractionTaskManagement',
    components: { Pagination },
    data() {
      return {
        tableKey: 0,
        list: [],
        total: 0,
        listLoading: false,
        ollamaOptions: [], // 存储Ollama地址选项
        listQuery: {
          page: 1,
          limit: 10,
          name: undefined,
          qzh: undefined,
          status: undefined
        },
        dialogVisible: false,
        dialogTitle: '',
        temp: {
          id: undefined,
          name: '',
          qzh: '',
          ollama_url: '',
          lbh:"",
          limit: 0, 
          status: 0
        },
        rules: {
          name: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
          qzh: [{ required: false, message: '请输入全宗号', trigger: 'blur' }],
          lbh: [{ required: false, message: '请输入类别号', trigger: 'blur' }],
          ollama_url: [{ required: true, message: "请选择ollama",   trigger: 'blur' }]
        }
      }
    },
    created() {
      this.getList()
      this.getOllamaOptions() // 初始化时获取Ollama地址选项
    },
    methods: {
      async getOllamaOptions() {
        try {
          const response = await api('getOllamaUrls')
          if (response.code === 200) {
            this.ollamaOptions = response.data.map(item => ({
              label: item.ip,
              value: item.ip
            }))
          }
        } catch (error) {
          console.error('获取Ollama服务地址失败:', error)
          this.$message.error('获取Ollama服务地址失败')
        }
      },
      async getList() {
        this.listLoading = true
        try {
          const response = await api('getObtainList', this.listQuery)
          if (response.code === 200) {
            this.list = response.data.resultList
            this.total = response.totalCount
          }
        } catch (error) {
          console.error('获取列表失败:', error)
        }
        this.listLoading = false
      },
      resetTemp() {
        this.temp = {
          id: undefined,
          name: '',
          qzh: '',
          lbh: '',
          ollama_url: '',
          limit: 0,
          status: 0
        }
      },
      handleAdd() {
        this.resetTemp()
        this.dialogTitle = '添加抽取任务'
        this.dialogVisible = true
        this.getOllamaOptions() // 打开对话框时获取最新选项
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      handleEdit(row) {
        this.temp = Object.assign({}, row)
        this.dialogTitle = '编辑抽取任务'
        this.dialogVisible = true
        this.getOllamaOptions() // 打开对话框时获取最新选项
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      async saveData() {
        this.$refs['dataForm'].validate(async (valid) => {
          if (valid) {
            const action = this.temp.id ? 'updateObtain' : 'addObtain'
            try {
              const response = await api(action, this.temp)
              if (response.code === 200) {
                this.$notify({
                  title: '成功',
                  message: response.message || '操作成功',
                  type: 'success',
                  duration: 2000
                })
                this.dialogVisible = false
                this.getList()
              }
            } catch (error) {
              console.error('保存失败:', error)
            }
          }
        })
      },
      async handleDelete(row, index) {
        this.$confirm('此操作将永久删除该任务, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          try {
            const response = await api('deleteObtain', { id: row.id })
            if (response.code === 200) {
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
              this.list.splice(index, 1)
            }
          } catch (error) {
            console.error('删除失败:', error)
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      async handleStart(row) {
        try {
          const response = await api('startObtain', { id: row.id })
          if (response.code === 200) {
            this.$notify({
              title: '成功',
              message: '任务已启动',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }
        } catch (error) {
          console.error('启动失败:', error)
        }
      },
      async handleStop(row) {
        try {
          const response = await api('stopObtain', { id: row.id })
          if (response.code === 200) {
            this.$notify({
              title: '成功',
              message: '任务已停止',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }
        } catch (error) {
          console.error('停止失败:', error)
        }
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      handleReset() {
        this.listQuery = {
          page: 1,
          limit: 10,
          name: undefined,
          qzh: undefined,
          status: undefined
        }
        this.getList()
      },
      viewQueue(row) {
        this.$router.push(`/extractbatch/queuelist?taskId=${row.id}`)
      },
      viewAllQueue() {
        this.$router.push('/extractbatch/queuelist')
      }
    }
  }
  </script>
  
  <style lang="scss" scoped>
  .app-container {
    padding: 20px;
    
    .filter-container {
      background-color: #fff;
      padding: 15px;
      border-radius: 4px;
      box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
    }
  
    .filter-left {
      flex: 1;
    }
  
    .filter-right {
      display: flex;
      align-items: center;
    }
    
    .statusPie {
      display: inline-block;
      width: 8px;
      height: 8px;
      border-radius: 50%;
      margin-right: 5px;
      
      &.success {
        background-color: #67C23A;
      }
      
      &.warning {
        background-color: #E6A23C;
      }
      
      &.info {
        background-color: #909399;
      }
      
      &.danger {
        background-color: #F56C6C;
      }
    }
    
    .text {
      font-size: 12px;
      vertical-align: middle;
    }
  }
  
  .dialog-footer {
    text-align: right;
    padding-top: 20px;
  }
  </style>